/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  ToolbarAndroid,
  TouchableHighlight,
  Dimensions,
  ListView,
  DeviceEventEmitter,
  Platform,
  PixelRatio
} from 'react-native';


import {CachedImageBackground} from "react-native-img-cache";

import Common from '../../../component/common';
import ScreenUtils from '../../../component/ScreenUtils';
import Toast from 'react-native-root-toast';


import BriefIntroduction from '../../specialColumn/briefIntroduction';
import ColumnDetails from '../../specialColumn/columnDetails';
import ColumnSearch from '../../search/columnSearch';



export default class subscriptionItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
  		dataSource: new ListView.DataSource({
          	rowHasChanged: (row1, row2) => row1 !== row2,
        	}),
  		showDeleteButton: this.props.showDeleteButton,
  		sectionTitle: this.props.sectionTitle,
  		rows :this.props.data,
  		classType:this.props.classType,
      showTitle:this.props.showTitle,
      deleteArr:[],
      dataLength:this.props.data.length
    };
    this.selectArr=[];
    this.openScroll=[]
  }
  componentWillReceiveProps(nextProps){
    if(nextProps.data != this.props.data){
        this.setState({
            rows:nextProps.data,
            dataSource: this.state.dataSource.cloneWithRows(this.state.rows),
            dataLength:nextProps.data.length,
            deleteArr:[]
        })
        this.selectArr=[];
         
    }
    if(this.openScroll.length>0){
      this.openScroll.map((item,key)=>{
          item.scrollTo({ x: 0, y: 0, animated: false });
          this.openScroll=[]
      })
    }
  	
  }
  componentWillUnmount() {
    
  }
  componentDidMount(){
  	this.setState({
  		dataSource: this.state.dataSource.cloneWithRows(this.state.rows),
  	})
  }
  
 handleDelete(rowIndex,entityId,target){
  	let formData = new FormData();
	formData.append("entityId",entityId);
	formData.append("userToken",this.props.userToken);
	Common.fetchData("POST", "/userCenter/collect/delete", formData, (responseData) => {
		
		// let arr= JSON.parse(JSON.stringify(this.state.rows));
		// arr.splice(rowIndex,1);
		// this.setState({
		// 	rows: arr,
		//   	dataSource: this.state.dataSource.cloneWithRows(arr),
		//   	dataLength:this.state.rows.length
		// });
		// if(this.state.dataLength>0 && this.state.dataLength-1 != rowIndex){
		// 	target.scrollTo({x: 0, y: 0, animated: false});
		// }
		// DeviceEventEmitter.emit("dealCollection",this.state.classType);
    let isShowTitle=this.state.dataLength;
    let showTitle = isShowTitle==1 ? false :true;
    this.selectArr.push(entityId);
      this.setState({
        deleteArr:this.selectArr,
        dataLength:isShowTitle-1,
        showTitle:showTitle
      });
    target.scrollTo({x: 0, y: 0, animated: false});
		Toast.show("删除成功",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
		
	},() => {
		Toast.show("删除失败",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	},() => {
		Toast.show("网络错误",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	});
  }
  render() {
  	let propDataLength = this.state.rows.length;
  	if(propDataLength===0){
  		return null;
  	}else{
      let marginStyle = this.state.dataLength>0 ? {
        
      } : {};
		return(
		<View style={styles.collectionColumn}>
      			{
      				this.state.showTitle　?　
      					<Text style={styles.collectionCategory}>
      						{this.state.sectionTitle}
      						{
      							this.props.totalPage ? <Text>({String(this.props.totalPage)})</Text> :null
      						}
      					</Text>　: null
      			}
      			{
      				this.props.showTotalData ?
      					<Text style={styles.collectionCategory}>
      							 <Text>共{String(this.props.totalPage)}条</Text>
      					</Text>　: null
      			}
      			<View style={[styles.Item,marginStyle]}>
          {
            this.state.rows.map((item,key)=>{
              return this.renderSubscription(item,key);
            })
          }
					{
						this.props.pagation ?
							<TouchableOpacity style={styles.showMore}  onPress={() => Common.onForward(this.props.chageThis,ColumnSearch,ColumnSearch,this.props.keywords,this.props.totalPage)}>
								<Image source = {require('../../../images/toBottom.png')}/>
								<Text style={{marginLeft:10,fontSize:ScreenUtils.scaleSize(20),}}>展开</Text>
							</TouchableOpacity> : <View style={styles.seperatorCell}></View>
					}
				</View>
		</View>
		)  		
  	}
  }
  
  showDeleteButton(ev,target){
  	if(this.startLocation>this.moveLocation){
  		target.scrollToEnd({animated: true});
      this.openScroll.push(target);
  	}else{
  		target.scrollTo({x:0,y:0,animated: true});
  	}
  }
  
  renderSubscription(data,rowID) {
  	var _scrollView: ScrollView;
  	var mydata = Common.keyWordHighlight(data.specialColumnTitle);
 	  var specialColumnSubject = Common.keyWordHighlight(data.specialColumnSubject);
 	  var columnTitle = Common.cancelHightlight(data.specialColumnTitle);
    var Vheight = ScreenUtils.scaleSize(330);
    var vMarginBottom=ScreenUtils.scaleSize(12);
    this.state.deleteArr.map((item,key)=>{
      if(item==data.id){
        Vheight=0;
        vMarginBottom=0;
      }
    })
    return (
      <ScrollView
      	horizontal = {true}
      	showsHorizontalScrollIndicator = {false}
      	ref={(scrollView) => { _scrollView = scrollView; }}
      	contentContainerStyle={{marginBottom:vMarginBottom,borderWidth:0,height:Vheight,overflow:"hidden"}}
      	onTouchStart={(event)=>{
      		this.startLocation=event.nativeEvent.pageX
      	}}
      	onTouchMove={(event)=>{
      		this.moveLocation=event.nativeEvent.pageX
      	}}
      	onScrollEndDrag={(event)=>{
      		 this.showDeleteButton(event,_scrollView);
      	}}
        key={rowID}
        bounces={false}
      >
	      <TouchableHighlight underlayColor="#fafafa" delayPressIn={100}  style ={[styles.subItemContainer,{height:Vheight,marginBottom:vMarginBottom,overflow:"hidden"}]} 
	      	onPress={() => {
		      		if(parseInt(data.type)== 8){
		      			Common.onForward(this.props.chageThis, BriefIntroduction,"", data.id);
		      		}else if(parseInt(data.type)== 9){
		      			Common.onForward(this.props.chageThis, ColumnDetails,columnTitle, data.id,"","no","Normal","true");
		      		}
	      		}
	      	}
	      >
          <View style ={{flex:1,flexDirection:"row"}}>
    			  <View style={styles.subItemConWrap}>
    				  <View style={styles.userAbout}>
      					<View style={styles.userImgWrap}>
      						{
      							data.userPic ?
      								<Image 
      									style={styles.userImg} 
      									source={{uri: data.userPic}} /> :
      								<Image style={styles.userImg} source = {require('../../../images/me/User.png')}/>
      						}
      						
      					</View>
      					<View style={styles.userInfo}>
      						<Text style={styles.userName}>{data.userName}</Text>
      						<Text 
      							style={styles.userRanking}
      							numberOfLines = {2}
      						>
      							{data.userRank}
      						</Text>
      					</View>
    				  </View>
    				  <View style={styles.subItemAbout}>
      					{
      						!this.props.search ? <Text style={styles.subItemTitle} numberOfLines = {2}>{data.specialColumnTitle}</Text> :
      						<Text style={styles.subItemTitle} numberOfLines = {2}>
      								{
      						          	mydata.map((item,i)=>{
      						          		if(item.hightLight){
      						          			return(
      						          				<Text key={i} style={{color:"red"}}>{item.data}</Text>
      						          			)
      						          		}else{
      						          			return(
      						          				<Text key={i}>{item.data}</Text>
      						          			)
      						          		}
      						          	})
      					        	}
      						</Text>
      					}
      					<View style={styles.subMagazine}>
      						{
      							!this.props.search ? <Text style={styles.subMagazineText} numberOfLines = {2}>{data.specialColumnSubject} </Text> :
      							<Text style={styles.subMagazineText} numberOfLines = {2}>
      								{
      						          	specialColumnSubject.map((item,i)=>{
      						          		if(item.hightLight){
      						          			return(
      						          				<Text key={i} style={{color:"red"}}>{item.data}</Text>
      						          			)
      						          		}else{
      						          			return(
      						          				<Text key={i}>{item.data}</Text>
      						          			)
      						          		}
      						          	})
      					        	}
      							</Text>
      						}
      					</View>
    				  </View>
    			  </View>
      			<View style={styles.subItemImgCon}>
      				<View style={styles.subItemImgWrap}>
      					{
      						data.specialColumnPic1 ?
      							<CachedImageBackground 
      								style={styles.subItemcoverImg} 
      								source={{uri: data.specialColumnPic1 }}
      							/> : <View style={[styles.subItemImgWrap,{borderWidth:1,borderColor:"#ededed"}]}><Text style={styles.noImg}>暂无图片</Text></View>
      					}
      					
      				</View>
      			</View>
          </View>
	      </TouchableHighlight>
	      {
	      	this.state.showDeleteButton ?
		      (
		      	<TouchableOpacity 
		      		style={styles.deleteWrap} 
		      		onPress={()=>{
		      			this.handleDelete(rowID,data.id,_scrollView)
		      			}
		      		}
		      	>
			      <Text style={styles.deleteText}>删除</Text>
			    </TouchableOpacity>
		      ):null
	      }
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  subItemContainer:{
    width:Dimensions.get('window').width,
    height: ScreenUtils.scaleSize(330),
  	backgroundColor:"#fff",
  	flexDirection:"row",
  	borderBottomWidth:1,
    borderTopWidth:1,
  	borderColor:"#ebebeb",
  },
  subItemConWrap:{
  	flex:1,
  	flexDirection:"column",
  	marginBottom:ScreenUtils.scaleSize(42),
  	marginLeft:ScreenUtils.scaleSize(30),
  	paddingLeft:ScreenUtils.scaleSize(10),
  	paddingRight:ScreenUtils.scaleSize(10),
  },
  userAbout:{
  	height:ScreenUtils.scaleSize(130),
  	borderBottomWidth:1/PixelRatio.get(),
  	borderColor:"#d2d2d2",
  	flexDirection:"row",
  	alignItems:"center",
  },
  userImgWrap:{
  	width:ScreenUtils.scaleSize(76),
  	height:ScreenUtils.scaleSize(76),
  },
  userImg:{
  	width:ScreenUtils.scaleSize(76),
  	height:ScreenUtils.scaleSize(76),
  	borderRadius:ScreenUtils.scaleSize(76)/2,
  },
  userInfo:{
  	flex:1,
  	paddingLeft:ScreenUtils.scaleSize(26),
  	flexDirection:"column",
  	justifyContent:"center",
  },
  userName:{
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#000",
  },
  userRanking:{
  	fontSize:ScreenUtils.scaleSize(18),
  	color:"#939393",
  	lineHeight:Math.round(ScreenUtils.scaleSize(30)),
  },
  subItemAbout:{
  	flex:1,
  	flexDirection:"column",
  	justifyContent:"space-around",
  },
  subItemTitle:{
  	color:"#000",
  	paddingTop:ScreenUtils.scaleSize(5),
  	fontSize:ScreenUtils.scaleSize(30),
  },
  subMagazine:{
  	flexDirection:"row",
  },
  subMagazineText:{
  	fontSize:ScreenUtils.scaleSize(20),
  	color:"#939393",
  	marginBottom:ScreenUtils.scaleSize(5),
  	lineHeight:Math.round(ScreenUtils.scaleSize(30)),
  },
  subItemImgCon:{
  	width:ScreenUtils.scaleSize(225),
  	justifyContent:"center",
  	alignItems:"center",
  },
  subItemImgWrap:{
  	width:ScreenUtils.scaleSize(183),
  	height:ScreenUtils.scaleSize(246),
  	position:"relative",
  	justifyContent:"center",
  	alignItems:"center",
  },
  noImg:{
  	color:"#ededed",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  subItemcoverImg:{
  	width:ScreenUtils.scaleSize(183),
  	height:ScreenUtils.scaleSize(246),
  },
  subItemStatus:{
  	position:"absolute",
  	right:0,
  	top:0,
  	width:ScreenUtils.scaleSize(54),
  	height:ScreenUtils.scaleSize(54),
  },
  coverIcon:{
  	width:ScreenUtils.scaleSize(54),
  	height:ScreenUtils.scaleSize(54),
  },
  subItemStatusText:{
  	position:"absolute",
  	right:0,
  	top:0,
  	width:ScreenUtils.scaleSize(54),
  	height:ScreenUtils.scaleSize(34),
  	textAlign:"center",
  	fontSize:ScreenUtils.scaleSize(12),
  	marginTop:ScreenUtils.scaleSize(10),
  	color:"#fff",
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
    height:ScreenUtils.scaleSize(330),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#939393",
  	paddingTop:ScreenUtils.scaleSize(12),
    paddingBottom:ScreenUtils.scaleSize(12),
  },
  Item:{
  	borderColor:"#ededed",
  },
  showMore:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(78),
  	backgroundColor:'#fff',
  	borderBottomWidth:1,
  	borderColor:'#ebebeb',
  	flexDirection:"row",
  	marginTop:-ScreenUtils.scaleSize(12),
  },
  seperatorCell:{
  	backgroundColor:"#fff",
  	marginTop:-ScreenUtils.scaleSize(12),
  }
});